package com.yunhoo.zh.db.impl;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.zh.model.User;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UserImpl {

    private static final String NAMESPACE = "user.";

    /**
     * 登录
     *
     * @param User user 用户
     * @return int 状态标识 1：成功 -1：数据库异常 -2：用户名不存在 -3：密码错误
     */
    public static long login(User user) {
        Long id_u;
        SqlMapClient sqlmap = IbatisTemplate.getSqlMapClient();
        try {
            sqlmap.startTransaction();

            id_u = queryByUserName(sqlmap, user.getUserName());
            if (id_u == null) return -2;

            id_u = queryByUserNameAndPwd(sqlmap, user.getUserName(), user.getPwd());
            if (id_u == null) return -3;

            sqlmap.commitTransaction();
        } catch (SQLException ex) {
            Logger.getLogger(RegisterImpl.class.getName()).log(Level.SEVERE, null, ex);

            /* 异常，返回失败标识 */
            return -1;
        } finally {
            try {
                sqlmap.endTransaction();
            } catch (SQLException ex1) {
                Logger.getLogger(RegisterImpl.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }

        /* 返回标识 */
        return id_u;
    }

    /**
     * 判断用户名是否存在
     *
     * @param String userName
     * @return long id_u
     */
    private static Long queryByUserName(SqlMapClient sqlmap, String userName) throws SQLException {
        return (Long) sqlmap.queryForObject(NAMESPACE + "queryByUserName", userName);
    }

    /**
     * 判断密码是否正确
     *
     * @param String userName,String pwd
     * @return long id_u
     */
    private static Long queryByUserNameAndPwd(SqlMapClient sqlmap, String userName, String pwd) throws SQLException {
        Map map = new HashMap();
        map.put("userName", userName);
        map.put("pwd", pwd);
        return (Long) sqlmap.queryForObject(NAMESPACE + "queryByUserNameAndPwd", map);
    }
}
